
#include "bird.h"
#include<QTimer>

Bird::Bird(QWidget *parent)
    : QWidget{parent}
{
    //加载鸟的图片
    for(int i=0;i<this->max;i++)
    {
        QString s=QString(":/Bird/bird%1").arg(i+1);//%1叫占位符
        this->m_Bird_Pix.load(s);
    }

    //设置鸟的尺寸(防止图片过大），后面还有设置窗口的尺寸
    this->setFixedSize(this->m_Bird_Pix.width(),this->m_Bird_Pix.height());

    //创建定时器的对象
    this->timer=new QTimer(this);

    //监听定时器发的信号
    connect(timer,&QTimer::timeout,[=](){
        QString s=QString(":/Bird/bird%1").arg(this->min++);
                    this->m_Bird_Pix.load(s);
        if(this->min>this->max)
        {
                        this->min=1;
        }
        //每次切图都要触发信号，让主场景收到
        emit changePix();
    });

    //创菜单
    this->m_Menu=new QMenu();

    //连接菜单中退出选项的信号槽
    connect(this->m_Menu->addAction("退出"),&QAction::triggered,[=](){
        exit(0);

});

}

//启动定时器的函数，很关键
void Bird::running()
{

    this->timer->start(50);
}

void Bird::mousePressEvent(QMouseEvent * e)
{
    //鼠标按下了就记录当前坐标分量（这里是左上角）
    this->m_Pos=e->globalPos()-((QWidget*)this->parent())->frameGeometry().topLeft();

    //鼠标一按住小鸟就是“真”
    this->mouseDown=true;

    //判断一下是不是鼠标右键
    if(e->button()==Qt::RightButton)
    {
        //弹出菜单,弹的位置和鼠标当前位置一致
        this->m_Menu->popup(QCursor::pos());
    }

    //如果右键后没点到退出
    connect(this->m_Menu,&QMenu::aboutToHide,[=](){
        this->mouseDown=false;
    });
}

void Bird::mouseMoveEvent(QMouseEvent * e)
{
    //这是获取拖拽后移动到的位置的信息，还要让主场景知道
    emit this->moving(e->globalPos()-this->m_Pos);
}

void Bird::mouseReleaseEvent(QMouseEvent *)
{
    //鼠标一释放就假
    this->mouseDown=false;
}
